# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: script_2.py
@time: 2024/10/23 19:04 
@desc: 

"""
from urllib.parse import quote
from sdk.temp.temp_supports import IsSolution
from sdk.utils.util_class import PathParser
from sdk.utils.util_times import TimeProcess


class Solution(IsSolution):
    """

    """

    def __init__(self):
        super(Solution, self).__init__()
        self.desc = f"script2_excel-jsonl"
        print(self.desc)
        self.time = TimeProcess()

    def excel_jsonl(self, file, filename):
        """

        :param file:
        :param filename:
        :return:
        """
        for args in self.excel.read_yield_xlsx_by_xlrd(file):
            try:
                print(args)
                session_id = self.get_one_from_yield_args(args, "session_id")
                system_setting = self.get_one_from_yield_args(args, "system_setting")
                self.success_lis.append({
                    "session_id": session_id,
                    "src": [system_setting],
                    "tgt": [
                        "好的，我将遵守您上面的系统设定。"
                    ]
                })
            except Exception as e:
                print(e, e.__traceback__.tb_lineno)
        save_file = self.folder.merge_path([self.save_path, f"result_{filename}.jsonl"])
        self.jsonl.write_to_jsonl(save_file,
                                  self.success_lis)
        self.success_lis = []
        return f"result_{filename}.jsonl"

    def jsonl_excel(self, file, filename):
        """

        :param file:
        :param filename:
        :return:
        """
        mode = self.mode
        if mode == "1":
            print("输入导出模式:[1:全字段导出]")
            mode = True
        elif mode == "0":
            print("输入导出模式:[0:只导出session_id+annotator_id]")
            mode = False
        else:
            raise ValueError("mode must in (1,0)")
        headers = []
        for args in self.jsonl.read_yield_jsonl(file):
            try:
                if mode:
                    out = []
                    headers = ['session_id', 'tgt', 'labeled_src', 'labeled_tgt', 'response_recom', 'annotated_flag',
                               'annotator_id', 'update_time', 'review_flag', 'reviewer_id', 'src']

                    for i in headers:
                        v = args.get(i, "")
                        if isinstance(v, list):
                            if len(v) > 0:
                                if None in v:
                                    v = [i if i is not None else "" for i in v]
                                    if len(v) > 0:
                                        v = self.json.dumps(v, indent=None)
                                        # v = "".join(v)

                                else:
                                    v = "".join(v)
                        out.append(v)
                else:
                    session_id = args["session_id"]
                    annotator_id = args["annotator_id"]
                    out = [session_id, annotator_id]
                    headers = ["session_id", "annotator_id"]

            except Exception as e:
                print(e, e.__traceback__.tb_lineno, args["session_id"])
            self.success_lis.append(out)
            if args.get("labeled_src") and args.get("labeled_tgt"):
                labeled_src = args.get("labeled_src")
                labeled_tgt = args.get("labeled_tgt")
                print(args["session_id"], len(labeled_src), len(labeled_tgt))

                for i, j in zip(labeled_src, labeled_tgt):
                    tmp = ["" for i in range(len(headers))]
                    tmp[1] = i
                    tmp[2] = j
                    self.success_lis.append(tmp)

        save_file = self.folder.merge_path([self.save_path, f"result_{filename}.xlsx"])
        self.excel.write(save_file, [self.success_lis],
                         [headers])
        self.success_lis = []

        return f"result_{filename}.xlsx"

    def process(self, data):
        """

        :return:
        """

        data["Desc"] = self.desc
        self.save_path = "static/download"
        self.mode = data.get("mode", "1")
        in_file = "tmp/uploads/"+data["input_file"]
        file_obj = PathParser(in_file)
        filename = f"result_{file_obj.name}_{self.time.get_normal_date()}"
        download_file = ""
        if file_obj.tail == "xlsx":
            download_file = self.excel_jsonl(in_file, filename)
        elif file_obj.tail == "jsonl":
            download_file = self.jsonl_excel(in_file, filename)
        else:
            raise NameError("文件格式错误，支持xlsx/jsonl")
        download_file = download_file.replace('\\', '/')
        data["ScriptResults"] = download_file
        return data
